#include "choosefriendwidget.h"
#include <QScrollArea>
#include <QScrollBar>
#include "debug.h"
#include <QLabel>
#include <QPainter>


/**********************************************************************************************
 * 供选择的一条好友列表
 **********************************************************************************************/
ChooseFriendWidget::ChooseFriendWidget(QWidget *parent, QString userId)
    :QDialog(parent)
    ,userId(userId)
{
    //1.设计基本属性
    this->setFixedSize(750,550);
    this->setWindowTitle("选择好友");
    this->setWindowIcon(QIcon(":/resource/LOGO.png"));
    this->setAttribute(Qt::WA_DeleteOnClose);
    this->setStyleSheet("QDialog {background-color:rgb(255,255,255);}");

    //2.创建布局管理器
    QHBoxLayout* hlayout = new QHBoxLayout();
    hlayout->setSpacing(0);
    hlayout->setContentsMargins(0,0,0,0);
    this->setLayout(hlayout);

    //3.针对左侧窗口做初始化
    initLeft(hlayout);
    //4.针对右侧窗口初始化
    initRight(hlayout);
    //5.加载数据到窗口中
    initData();
}

void ChooseFriendWidget::initLeft(QHBoxLayout *hlayout)
{
    //1.创建滚动区域
    QScrollArea* scrollArea = new QScrollArea();
    scrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    scrollArea->setWidgetResizable(true);
    scrollArea->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal { height: 0px;}");
    scrollArea->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width: 2px; background-color: rgb(255, 255, 255) }");
    scrollArea->setStyleSheet("QScrollArea { border:none; }");
    hlayout->addWidget(scrollArea, 1);

    //2.创建QWidget,设置到滚动区域中
    leftContainer = new QWidget();
    leftContainer->setObjectName("totalContainer");
    leftContainer->setStyleSheet("#totalContainer { background-color: rgb(255, 255, 255); }");
    scrollArea->setWidget(leftContainer);

    // 3. 创建左侧子窗口内部的 垂直布局管理器
    QVBoxLayout* vlayout = new QVBoxLayout();
    vlayout->setSpacing(0);
    vlayout->setContentsMargins(0, 0, 0, 0);
    vlayout->setAlignment(Qt::AlignTop);
    leftContainer->setLayout(vlayout);

#ifdef TEST_UI
    QIcon defaultAvatar(":/resource/lion.png");
    for (int i = 0; i < 30; ++i) {
        this->addFriend(QString::number(1000 + i),defaultAvatar, "张三" + QString::number(i),false);
    }
#endif
}

void ChooseFriendWidget::initRight(QHBoxLayout *hlayout)
{
    // 1. 创建右侧的布局管理器
    QGridLayout* gridLayout = new QGridLayout();
    gridLayout->setContentsMargins(20, 0, 20, 20);
    gridLayout->setSpacing(10);
    hlayout->addLayout(gridLayout, 1);

    // 2. 创建 "提示" label
    QLabel* tipLabel = new QLabel();
    tipLabel->setText("选择联系人");
    tipLabel->setFixedHeight(30);
    tipLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    tipLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    tipLabel->setStyleSheet("QLabel { font-size: 16px; font-weight: 700}");

    // 3. 创建滚动区域
    QScrollArea* scrollArea = new QScrollArea();
    scrollArea->setWidgetResizable(true);
    scrollArea->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width: 2px; background-color: rgb(255, 255, 255);}");
    scrollArea->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal {height: 0px;}");
    scrollArea->setStyleSheet("QScrollArea {border: none;}");
    scrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    // 4. 创建滚动区域中的 QWidget
    rightContainer = new QWidget();
    rightContainer->setObjectName("selectedContainer");
    rightContainer->setStyleSheet("#selectedContainer { background-color: rgb(255, 255, 255); }");
    scrollArea->setWidget(rightContainer);

    // 5. 创建 selectedContainer 中的 "垂直布局"
    QVBoxLayout* vlayout = new QVBoxLayout();
    vlayout->setSpacing(0);
    vlayout->setContentsMargins(0, 0, 0, 0);
    vlayout->setAlignment(Qt::AlignTop);
    rightContainer->setLayout(vlayout);

    // 6. 创建底部按钮
    QString style = "QPushButton { color: rgb(7, 191, 96); background-color: rgb(240, 240, 240); border: none; border-radius: 5px;}";
    style += "QPushButton:hover { background-color: rgb(220, 220, 220); }";
    style += "QPushButton:pressed { background-color: rgb(200, 200, 200); }";

    QPushButton* okBtn = new QPushButton();
    okBtn->setFixedHeight(40);
    okBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    okBtn->setText("完成");
    okBtn->setStyleSheet(style);

    QPushButton* cancelBtn = new QPushButton();
    cancelBtn->setFixedHeight(40);
    cancelBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    cancelBtn->setText("取消");
    cancelBtn->setStyleSheet(style);

    // 7. 把上述控件添加到布局中
    gridLayout->addWidget(tipLabel, 0, 0, 1, 9);
    gridLayout->addWidget(scrollArea, 1, 0, 1, 9);
    gridLayout->addWidget(okBtn, 2, 1, 1, 3);
    gridLayout->addWidget(cancelBtn, 2, 5, 1, 3);


#if 0
    // 此处的数据通过勾选左侧列表来生成.
    QIcon defaultAvatar(":/resource/lion.png");
    for (int i = 0; i < 10; ++i) {
        this->addSelectedFriend(defaultAvatar, "张三" + QString::number(i));
    }
#endif

    //8.关联完成按钮的信号槽
    connect(okBtn,&QPushButton::clicked,this,&ChooseFriendWidget::clickOkBtn);

    connect(cancelBtn,&QPushButton::clicked,this,[=](){
        this->close();
    });
}

void ChooseFriendWidget::initData()
{
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    QList<model::UserInfo>* friendList = dataCenter->getFriendList();
    if(friendList == nullptr)
    {
        LOG() << "加载数据时，好友列表为空";
        return;
    }
    for (auto it = friendList->begin(); it != friendList->end(); ++it) {
        if (it->userId == this->userId) {
            this->addSelectedFriend(it->userId, it->avatar, it->nickName);
            this->addFriend(it->userId, it->avatar, it->nickName, true);
        } else {
            this->addFriend(it->userId, it->avatar, it->nickName, false);
        }
    }
}

void ChooseFriendWidget::clickOkBtn()
{
    //1.根据选中的好友，构建要创建群聊会话的用户Id列表
    QList<QString> userIdList = generateMemberList();
    if(userIdList.size() < 3)
    {
        Toast::showMessage("群聊人数必须大于3,无法创建群聊");
        return;
    }

    //2.发送网络请求,创建群聊
    DataCenter* dataCenter = DataCenter::getInstance();
    dataCenter->createGroupChatSessionAsync(userIdList);

    //3.关闭当前窗口
    this->close();
}

QList<QString> ChooseFriendWidget::generateMemberList()
{
    QList<QString> userIdList;
    //1.先把自己添加到列表中
    DataCenter* dataCenter = DataCenter::getInstance();
    if(dataCenter->getMyself() == nullptr)
    {
        LOG() << "个人信息未加载，dataCenter->getMyself() == nullptr";
        return userIdList;
    }
    userIdList.push_back(dataCenter->getMyself()->userId);

    //2.将选中的好友添加进列表
    //网格布局转垂直布局
    QVBoxLayout* layout = dynamic_cast<QVBoxLayout*>(rightContainer->layout());
    for(int i = 0; i < layout->count(); ++i)
    {
        auto* item = layout->itemAt(i);
        if(item == nullptr || item->widget() == nullptr)
        {
            continue;
        }

        auto* chooseFriendItem = dynamic_cast<ChooseFriendItem*>(item->widget());
        userIdList.push_back(chooseFriendItem->getUserId());
    }
    return userIdList;
}


void ChooseFriendWidget::addFriend(const QString& userId,const QIcon &avatar, const QString &name,bool checked)
{
    ChooseFriendItem* chooseFriendItem = new ChooseFriendItem(this,userId,avatar,name,checked);
    leftContainer->layout()->addWidget(chooseFriendItem);
}

void ChooseFriendWidget::addSelectedFriend(const QString& userId,const QIcon &avatar, const QString &name)
{
    ChooseFriendItem* chooseFriendItem = new ChooseFriendItem(this,userId,avatar,name,true);
    rightContainer->layout()->addWidget(chooseFriendItem);
}

void ChooseFriendWidget::deleteSelectedFriend(const QString& userid)
{
    // 遍历rightContainer 中的每个 Item, 对比每个 Item 里的 userId , 是否是要删除的 userId
    QVBoxLayout* vlayout = dynamic_cast<QVBoxLayout*>(rightContainer->layout());
    for(int i = vlayout->count()-1; i >= 0; --i)
    {
        QLayoutItem* item = vlayout->itemAt(i); //获得layout中的一条Item
        if(item == nullptr || item->widget() == nullptr)
        {
            continue;
        }

        ChooseFriendItem* chooseFriendItem = dynamic_cast<ChooseFriendItem*>(item->widget());
        //判断当前Item的userId
        if(chooseFriendItem->getUserId() != userid)
        {
            continue;
        }

        //找到了
        vlayout->removeItem(item);
        //处直接使用 delete 可能导致程序直接崩溃. 因为 delete 该对象的时候, 该对象内部的 QCheckBox 还在使用中 (触发着信号槽呢)
        chooseFriendItem->deleteLater();
    }

    //再遍历一下左侧列表, 把左侧列表中对应 item 的 checkBox 勾选状态取消掉
    QVBoxLayout* vlayoutLeft = dynamic_cast<QVBoxLayout*>(leftContainer->layout());
    for (int i = 0; i < vlayoutLeft->count(); ++i) {
        auto* item = vlayoutLeft->itemAt(i);
        if (item == nullptr || item->widget() == nullptr) {
            continue;
        }
        ChooseFriendItem* chooseFriendItem = dynamic_cast<ChooseFriendItem*>(item->widget());
        if (chooseFriendItem->getUserId() != userid) {
            continue;
        }
        // 取消 checkBox 选中状态
        chooseFriendItem->getCheckBox()->setChecked(false);
    }
}


/**********************************************************************************************
 * 一条好友列表
 **********************************************************************************************/
ChooseFriendItem::ChooseFriendItem(ChooseFriendWidget* owner,const QString& userId,const QIcon &avatar, const QString &name,bool checked)
    :isHover(false)
    ,userId(userId)
{
    //1.设置基本属性
    this->setFixedHeight(50);
    this->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);

    //2.设置布局管理器
    QHBoxLayout* hlayout = new QHBoxLayout();
    hlayout->setSpacing(5);
    hlayout->setContentsMargins(20,0,20,0);
    this->setLayout(hlayout);

    // 3. 创建复选框
    checkBox = new QCheckBox();
    checkBox->setChecked(checked);  //设置当前复选框是否被选中，将其放在右边后，保留该效果
    checkBox->setFixedSize(25, 25);
    QString style = "QCheckBox { background-color: transparent; } QCheckBox::indicator { width: 25px; height: 25px; image: url(:/resource/unchecked.png);}";
    style += "QCheckBox::indicator:checked { image: url(:/resource/checked.png);}";
    checkBox->setStyleSheet(style);

    // 4. 创建头像
    avatarBtn = new QPushButton();
    avatarBtn->setFixedSize(40, 40);
    avatarBtn->setIconSize(QSize(40, 40));
    avatarBtn->setStyleSheet("QPushButton{ border:none;}");
    avatarBtn->setIcon(avatar);

    // 5. 创建名字
    nameLabel = new QLabel();
    nameLabel->setText(name);
    nameLabel->setStyleSheet("QLabel {background-color: transparent;}");

    // 6. 添加上述内容到布局管理器中
    hlayout->addWidget(checkBox);
    hlayout->addWidget(avatarBtn);
    hlayout->addWidget(nameLabel);

    //7.添加信号槽，实现选中添加至右边，取消在右边同步删除的功能
    connect(checkBox,&QCheckBox::toggled,this,[=](bool checked){
        if(checked)
        {
            //勾选了复选框, 把当前这个 Item, 添加到右侧的已选择区域
            owner->addSelectedFriend(userId,avatar,name);
        }
        else
        {
            owner->deleteSelectedFriend(userId);
        }
    });
}

void ChooseFriendItem::paintEvent(QPaintEvent *event)
{
    (void) event;
    // 根据鼠标的进入状态, 来决定绘制成不同的颜色
    QPainter painter(this);
    if (isHover) {
        // 绘制成深色
        painter.fillRect(this->rect(), QColor(230, 230, 230));
    } else {
        // 绘制成浅色
        painter.fillRect(this->rect(), QColor(255, 255, 255));
    }
}

void ChooseFriendItem::enterEvent(QEnterEvent *event)
{
    (void) event;
    isHover = true;
    // update 相当于 "更新界面"
    this->update();
    // 或者使用下列代码
    // this->repaint();
}

void ChooseFriendItem::leaveEvent(QEvent *event)
{
    (void) event;
    isHover = false;
    this->update();
}






